<template>
  <div class="login">
    <h3 class="title">步尚集小程序管理系统</h3>
    <el-form
      ref="ruleFormRef"
      style="max-width: 600px"
      :model="ruleForm"
      status-icon
      :rules="rules"
      label-width="auto"
      class="demo-ruleForm"
      show-message="true"
    >
      <el-form-item prop="username">
        <el-input
          v-model="ruleForm.username"
          size="large"
          placeholder="请输入用户名"
        >
          <template #prefix>
            <el-icon :size="30"><User /></el-icon>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          v-model="ruleForm.password"
          size="large"
          placeholder="请输入密码"
          show-password
        >
          <template #prefix>
            <el-icon :size="30"><Lock /></el-icon>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          登录
        </el-button>
      </el-form-item>
    </el-form>
    <span class="toRegister" @click="toRegister">没账号？去注册</span>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from "vue";
import { LoginApi } from "./api/user";
import type { FormInstance, FormRules } from "element-plus";
import { User, Lock } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";
import { useStore } from "../store/user";


const router = useRouter();
const ruleFormRef = ref<FormInstance>();
const store = useStore();

const ruleForm = reactive({
  username: "",
  password: "",
});


// 表单校验规则
const rules = reactive<FormRules<typeof ruleForm>>({
  username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { max: 6, min: 6, message: "密码必须等于6位数", trigger: "blur" },
  ],
});

// 请求提交前做二次校验
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    console.log(valid);
    console.log(ruleFormRef);
    if (valid) {
      // 请求
      LoginApi(ruleForm).then((res) => {
        if (res.success) {
          // 存token
          localStorage.setItem("token",res.data.token);

          // 跳转
          router.push("/index");

          // 提示
          ElMessage({
            message: "登录成功",
            type: "success",
          });
        }
      });
    }
  });
};


// 跳转注册页面 
const toRegister = ()=>{
  router.push("/register");
}

</script>

<style lang="less" scoped>
.login {
  width: 400px;
  margin: 100px auto;
  text-align: center;
  :deep(.el-input__inner) {
    height: 50px;
  }
  :deep(.el-button--primary) {
    height: 40px;
    width: 100%;
  }
}
.title {
  color: #ffffff;
  margin-bottom: 20px;
}

.toRegister{
  color: #409eff;
  cursor: pointer;
}
</style>